package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-11-13
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private MinIOService minIOService;

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile file) {
        User user = UserThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        WmMaterial wmMaterial = new WmMaterial();
//        wmMaterial.setId(); //主键自增 不用处理

        String url = minIOService.upload(file);
        wmMaterial.setUrl(url); //上传到minio返回的url地址

        Integer userId = user.getUserId();
        wmMaterial.setUserId(userId);
        wmMaterial.setType(0); //素材类型            0 图片            1 视频"
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());

        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult<WmMaterial> listByCollection(WmMaterialDto dto) {
//        如果没有登录人 直接报错
        User user = UserThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();

//        是否收藏
        if (dto.getIsCollection()!=null) {
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
//        隐藏的条件 当前登录人  + 根据创建时间排序降序
        queryWrapper.eq(WmMaterial::getUserId,user.getUserId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
//        分页查询
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());

        Page<WmMaterial> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }
}
